package com.sso.shiro;

import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.springframework.data.redis.core.RedisTemplate;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Set;

/**
 * redis的Hash存储方式，缺点不能单独设置每一条数据的redis失效时间
 * @param <K>
 * @param <V>
 */
public class MyHashCache<K,V> implements Cache<K,V>,Serializable {
    private final String REDIS_SHIRO_CACHE = "shiro-cache:";
    private String cacheKey;
    private RedisTemplate<String, V> redisTemplate;

    public MyHashCache(String name, RedisTemplate client){
        this.cacheKey=this.REDIS_SHIRO_CACHE+name;
        this.redisTemplate = client;
    }

    @Override
    public V get(K key) throws CacheException {
        return (V) redisTemplate.boundHashOps(this.cacheKey).get(key);
    }

    @Override
    public V put(K key, V value) throws CacheException {
        V old = get(key);
        redisTemplate.boundHashOps(this.cacheKey).put(key,value);
        return old;
    }

    @Override
    public V remove(K key) throws CacheException {
        V old = get(key);
        redisTemplate.boundHashOps(this.cacheKey).delete(key);
        return old;
    }

    @Override
    public void clear() throws CacheException {
        redisTemplate.boundHashOps(this.cacheKey).delete();
    }

    @Override
    public int size() {
        return redisTemplate.boundHashOps(this.cacheKey).keys().size();
    }

    @Override
    public Set keys() {
        return redisTemplate.boundHashOps(this.cacheKey).keys();
    }

    @Override
    public Collection values() {
        List<Object> keys = redisTemplate.boundHashOps(this.cacheKey).values();
        return keys;
    }
}
